//
//  DHUserInfoViewController.m
//  DHKuaiYi
//
//  Created by xiaohuihui on 2016/11/13.
//  Copyright © 2016年 30-陈辉华. All rights reserved.
//

#import "DHUserInfoViewController.h"
#import "Masonry.h"
#import "DHUserInfoModel.h"
#import "DHUserInfoTableViewCell.h"
#import "DHProvincePicker.h"
#import "DHWeightHeightPicker.h"
#import <SVProgressHUD.h>
#import "CheckDataTool.h"

#define UserIconImageHeight 70

static NSString *UserInfoCellID = @"UserInfoCellID";

@interface DHUserInfoViewController () <UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

/*---------- 用户信息数组 ----------*/
@property (nonatomic, strong) NSArray *UserInfoList;

/*---------- 用户头像 ----------*/
@property (nonatomic, weak) UIImageView *userIconView;

/*---------- tableView ----------*/
@property (nonatomic, weak) UITableView *tableView;

@end

@implementation DHUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadUserInfoData];
}

- (BOOL)LocalHaveImage:(NSString *)key {
    NSUserDefaults* preferences = [NSUserDefaults standardUserDefaults];
    
    NSData* imageData = [preferences objectForKey:key];
    if (imageData) {
        return YES;
    }
    return NO;
}

- (void)viewWillAppear:(BOOL)animated {
    BOOL imageIsExited = [self LocalHaveImage:UserImageKey];
    if (imageIsExited) {
        
        NSData *imgData = [[NSUserDefaults standardUserDefaults] objectForKey:UserImageKey];
        self.userIconView.image = [UIImage imageWithData:imgData];
    } else {
        self.userIconView.image = [UIImage imageNamed:@"icon_bb"];
    }
}

#pragma mark - 加载个人信息数据
- (void)loadUserInfoData {
    //获取plist文件url
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"my.plist" withExtension:nil];
    NSArray *list = [NSArray arrayWithContentsOfURL:url];
    
    //保存数据的数组
    NSMutableArray *userInfoList = [NSMutableArray array];
    //遍历数组
    for (NSDictionary *dict in list) {
        DHUserInfoModel *userModel = [[DHUserInfoModel alloc] init];
        [userModel setValuesForKeysWithDictionary:dict];
        [userInfoList addObject:userModel];
    }
    self.UserInfoList = userInfoList.copy;
}

#pragma mark - 响应事件
/**
 切换图像
 */
- (void)changeHeadPortrait {
    //弹窗提示，相册或者相机
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    //添加操作
    UIAlertAction *camereAction =[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    //添加相册选择
    __weak typeof(self) weakself = self;
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //创建图片选择器
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        //设置类型
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePickerController.delegate = weakself;
        
        //允许图片修改
        imagePickerController.allowsEditing = YES;
        
        [weakself presentViewController:imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    //添加拍照、相册、取消选项
    [alertController addAction:camereAction];
    [alertController addAction:photoAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    //获取原始图片
    UIImage *newPhoto = [info objectForKey:UIImagePickerControllerEditedImage];
    
    self.userIconView.image = newPhoto;
    
    //保存数据
    [[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(newPhoto) forKey:UserImageKey];
    
    //关闭相册界面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

/**
 用户取消了操作
 */
- (void)imagePickerControllerDidCancel:(nonnull UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //取消选中
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //取出模型数据
    DHUserInfoTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    DHUserInfoModel *info = cell.userInfoModel;
    NSInteger index = indexPath.row;
    switch (index) {
        case 0:
        case 1:
        case 2:
        case 3:
            [self alertControllerWithUserInfoContent:info indexPath:indexPath];
            break;
        case 4:
        case 5:
            [self weightAndHeight:info indexPath:indexPath];
            break;
        case 6:
        case 7:
            [self provincePickerView:info indexPath:indexPath];
        default:
            break;
    }
}

- (void)provincePickerView:(DHUserInfoModel *)info indexPath:(NSIndexPath *)indexPath {
    
     DHProvincePicker *pickerView = [DHProvincePicker provincePicker];
    [pickerView show];
    
    __weak typeof(self) weakself = self;
    pickerView.pickerViewValueChangeBlock = ^(NSString *province, NSString *city){
        //拼接城市
        NSString *provinceCity = [province stringByAppendingFormat:@"-%@",city];
        
        //给数组赋值
        info.userInfoContent = provinceCity;
        
        //保存数据
        NSString *str =[info.title stringByAppendingFormat:@"Key"];
        [[NSUserDefaults standardUserDefaults] setObject:info.userInfoContent forKey:str];
        
        //刷新数据行
        [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    };
}

#pragma mark - pickerView
- (void)weightAndHeight:(DHUserInfoModel *)info indexPath:(NSIndexPath *)indexPath {
    
    DHWeightHeightPicker *weightPicker = [DHWeightHeightPicker weightHeightPicker];
    weightPicker.nameLabel.text = [NSString stringWithFormat:@"修改%@",info.title];
    //显示修改过的视图
    [weightPicker show];
    
    //有block使用弱指针
    __weak typeof(self) weakself = self;
    weightPicker.pickerViewValueChangeBlock = ^(NSString *numberString) {
        //1.先判断数字是否符合要求
        if (numberString.intValue < 60 && indexPath.row == 4) {
            [SVProgressHUD showErrorWithStatus:@"请认真身高数据!"];
            delay(1.5);
        } else if (numberString.intValue < 30 && indexPath.row == 5){
            [SVProgressHUD showErrorWithStatus:@"请认真体重数据"];
            delay(1.5);
        } else {
            
            //判断用什么公式
            if (indexPath.row == 4) {
                numberString = [NSString stringWithFormat:@"%@ cm",numberString];
                
            } else if (indexPath.row == 5){
                numberString = [NSString stringWithFormat:@"%@ kg",numberString];
            }
//            NSLog(@"%@",numberString);
            //给数组赋值
            info.userInfoContent = numberString;
            
            //保存数据
            NSString *str =[info.title stringByAppendingFormat:@"Key"];
            [[NSUserDefaults standardUserDefaults] setObject:info.userInfoContent forKey:str];
            
            //刷新数据行
            [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }

    };
}

#pragma mark - UIAlertController
- (void)alertControllerWithUserInfoContent:(DHUserInfoModel *)UserInfo indexPath:(NSIndexPath *)indexPath {
    
    //有block使用弱指针
    __weak typeof(self) weakself = self;
    
    //性别选择
    if (indexPath.row == 1) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
        
        UIAlertAction *womenAction = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //给数组赋值
            UserInfo.userInfoContent = @"女";
            
            //保存数据
            NSString *str =[UserInfo.title stringByAppendingFormat:@"Key"];
            [[NSUserDefaults standardUserDefaults] setObject:UserInfo.userInfoContent forKey:str];
            
            //刷新数据行
            [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        }];
        
        UIAlertAction *manAction = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //给数组赋值
            UserInfo.userInfoContent = @"男";
            
            //保存数据
            NSString *str =[UserInfo.title stringByAppendingFormat:@"Key"];
            [[NSUserDefaults standardUserDefaults] setObject:UserInfo.userInfoContent forKey:str];
            
            //刷新数据行
            [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
        }];
        
        //添加action
        [alertController addAction:womenAction];
        [alertController addAction:manAction];
        [alertController addAction:cancelAction];
        
        //弹出alertController
        [self presentViewController:alertController animated:YES completion:nil];
    } else {
        NSString *title = [NSString stringWithFormat:@"修改%@",UserInfo.title];
        
        //创建UIAlertController
        UIAlertController *textAlertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
        __weak UIAlertController *tempAlertCtrl = textAlertController;
        
        [textAlertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
            textField.placeholder = UserInfo.title;
            textField.textColor = [UIColor blueColor];
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.borderStyle = UITextBorderStyleRoundedRect;
        }];
        
        //添加取消按钮
        UIAlertAction *canelAciton = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [textAlertController addAction:canelAciton];
        
        //添加确定按钮
        UIAlertAction *ensureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            //1.取出文本框
            UITextField *textField = tempAlertCtrl.textFields.firstObject;
            //取出内容
            NSString *contentText = textField.text;
            
            //正则表达式判断
            if (indexPath.row == 3){
                BOOL mobilePhone = [CheckDataTool checkForMobilePhoneNo:contentText];
                if (!mobilePhone) {
                    [SVProgressHUD showErrorWithStatus:@"你输入的手机号格式有误"];
                    delay(1.5);
                    return ;
                }
                
            } else if (indexPath.row == 2){
                BOOL IDCard = [CheckDataTool checkForIdCard:contentText];
                if (!IDCard) {
                    [SVProgressHUD showErrorWithStatus:@"你输入的身份证号格式有误"];
                    delay(1.5);
                    return;
                }
            }
            
            //给数组赋值
            UserInfo.userInfoContent = contentText;
            
            //保存数据
            NSString *str =[UserInfo.title stringByAppendingFormat:@"Key"];
            [[NSUserDefaults standardUserDefaults] setObject:textField.text forKey:str];
            
            //刷新行
            [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            
        }];
        [textAlertController addAction:ensureAction];
        
        [self presentViewController:textAlertController animated:YES completion:nil];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.UserInfoList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DHUserInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:UserInfoCellID forIndexPath:indexPath];
    //取出数据赋值
    DHUserInfoModel *userInfoModel = self.UserInfoList[indexPath.row];
    NSString *str = [userInfoModel.title stringByAppendingFormat:@"Key"];
    userInfoModel.userInfoContent = [[NSUserDefaults standardUserDefaults] objectForKey:str];
    
    cell.userInfoModel = userInfoModel;
    
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic_cell_green_accessory_img"]];
    cell.accessoryView = imgView;
    
    return cell;
}

#pragma mark - UI布局
/**
 UI布局
 */
- (void)setupUI {
    //创建tableView
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    [self.view addSubview:tableView];
    tableView.rowHeight = 40;
    
    //遵守数据源、代理
    tableView.dataSource = self;
    tableView.delegate = self;
    
    [tableView registerClass:[DHUserInfoTableViewCell class] forCellReuseIdentifier:UserInfoCellID];
    self.tableView = tableView;
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 150)];
    //添加背景层
    UIImageView *backgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"07"]];
    [headerView addSubview:backgroundImage];
    
    //添加用户头像
    UIImageView *userIconView = [[UIImageView alloc] init];
    [headerView addSubview:userIconView];
    
    //添加点击头像的用户事件
    userIconView.userInteractionEnabled = YES;
    [userIconView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeHeadPortrait)]];
    
    //切圆形图像
    userIconView.layer.masksToBounds = YES;
    userIconView.layer.cornerRadius = UserIconImageHeight / 2;
    
    tableView.tableHeaderView = headerView;
    
    //自动布局
    [backgroundImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(headerView);
    }];
    
    [userIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(headerView.mas_centerX);
        make.bottom.mas_equalTo(headerView.mas_bottom).offset(-10);
        make.size.mas_equalTo(CGSizeMake(UserIconImageHeight, UserIconImageHeight));
    }];
    
    //记录属性
    self.userIconView = userIconView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
